package com.ve.searcher.extension

import java.io.IOException
import java.nio.charset.Charset
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
import java.nio.file.attribute.FileAttribute
import java.util.*

/**
 * see https://github.com/Glavo/kala/
 * path.extension
 *
 * */


inline fun Path.createFile(vararg attrs: FileAttribute<*>) = Files.createFile(this, *attrs)

inline fun Path.createDirectories(vararg attrs: FileAttribute<*>): Path = Files.createDirectories(this, *attrs)

inline fun Path.createDirectory(vararg attrs: FileAttribute<*>): Path = Files.createDirectory(this, *attrs)

inline fun Path.delete(): Unit = Files.delete(this)

inline fun Path.deleteIfExists(): Boolean = Files.deleteIfExists(this)

fun Path.deleteRecursively() {
    this.walkFileTree(object : AbstractFileVisitor<Path> {
        override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
            if (exc != null)
                throw exc
            dir.delete()
            return FileVisitResult.CONTINUE
        }

        override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
            file.delete()
            return FileVisitResult.CONTINUE

        }
    })
}

val Path.extension: String
    inline get() = this.fileName.toString().substringAfterLast('.', "")

val Path.nameWithoutExtension: String
    get() = fileName.toString().substringBeforeLast(".")


inline fun Path.size(): Long = Files.size(this)

inline fun Path.exists(vararg options: LinkOption): Boolean = Files.exists(this, *options)

inline fun Path.notExists(vararg options: LinkOption): Boolean = Files.notExists(this, *options)

inline fun Path.walkFileTree(visitor: FileVisitor<in Path>): Path =
        Files.walkFileTree(this, visitor)


inline fun Path.walkFileTree(maxDepth: Int, vararg options: FileVisitOption, visitor: FileVisitor<in Path>): Path =
        Files.walkFileTree(this, EnumSet.copyOf(options.asList()), maxDepth, visitor)

inline fun Path.readLines(charset: Charset = Charsets.UTF_8): List<String> = Files.readAllLines(this, charset)